package kr.couponplay.android.activity.message;

import java.util.List;

import kr.couponplay.android.activity.R;
import kr.couponplay.android.domain.BeanFactory;
import kr.couponplay.android.domain.message.MessageDao;
import kr.couponplay.android.domain.message.MessageList;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

@SuppressLint("HandlerLeak") 
public class MessageListFragment extends Fragment implements OnItemClickListener {
	protected MessageListViewAdapter messageListViewAdapter;
	protected ListView messageListView;
	private int position;
	private String providerCode;
	private List<MessageList.Item> messageItems;
	
	public static MessageListFragment newInstance(Context context, int position, String providerCode, List<MessageList.Item> messageItems) {
		MessageListFragment fragment = new MessageListFragment();
		fragment.position = position;
		fragment.providerCode = providerCode;
		fragment.messageItems = messageItems;
		return fragment;
	}
	
	public void onSaveInstanceState(Bundle state) {
        super.onSaveInstanceState(state);
        state.putInt("position", position);
        state.putString("providerCode", providerCode);
    }
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		if (savedInstanceState != null) {
			position = savedInstanceState.getInt("position");
			providerCode = savedInstanceState.getString("providerCode");
		}
		
		if (messageItems == null) {
			MessageList messageList = BeanFactory.getBean(getActivity(), MessageDao.class).selectMessageList(0);
			messageItems = messageList.getMessageItems(providerCode);
		}

		View onCreateView = inflater.inflate(R.layout.message_fragment, container, false);
		messageListView = (ListView) onCreateView.findViewById(R.id.message_list_view);
		messageListView.setOnItemClickListener(this);
		messageListViewAdapter = new MessageListViewAdapter(container.getContext(), R.layout.message_list_row, messageItems);
        messageListView.setAdapter(messageListViewAdapter);	

		return onCreateView;
	}
	
	@Override
	public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
		String message = "[" + messageListViewAdapter.getItem(position).getMessage() + "]<br/>";
        new AlertDialog.Builder(view.getContext())
            .setMessage(Html.fromHtml(message))
            .setNegativeButton("확인", null)
            .show();
	}

	public int getPosition() {
		return position;
	}
}
